package cn.com.dingtek.genius.manager.server.service;

import cn.com.dingtek.genius.manager.server.repository.db.entity.UserLoginLog;
import cn.com.dingtek.genius.manager.server.repository.db.entity.UserOperateLog;
import cn.com.dingtek.genius.manager.server.repository.db.manager.UserLoginLogManager;
import cn.com.dingtek.genius.manager.server.repository.db.manager.UserOperateLogManager;
import cn.com.dingtek.genius.manager.server.utils.DateTimeUtil;
import cn.com.dingtek.genius.manager.server.utils.MybatisPlusUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuxueli.poi.excel.ExcelExportUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class LogService {
    @Autowired
    private UserLoginLogManager userLoginLogManager;
    @Autowired
    private UserOperateLogManager userOperateLogManager;

    public JSONObject userLoginLogList(UserLoginLog param, int currentPage, int pageSize) {
        QueryWrapper<UserLoginLog> query = Wrappers.emptyWrapper();
        if (param != null) {
            query = MybatisPlusUtil.customEqQuery(null, "account_name", param.getAccountName());
        }

        IPage<UserLoginLog> page = userLoginLogManager.page(new Page<UserLoginLog>(currentPage, pageSize).setDesc("id"), query);
        return new JSONObject().fluentPut("total", page.getTotal())
                .fluentPut("records", page.getRecords());
    }

    public JSONObject userOperateLogList(UserOperateLog param, int currentPage, int pageSize) {
        QueryWrapper<UserOperateLog> query = Wrappers.emptyWrapper();
        if (param != null) {
            query = MybatisPlusUtil.customEqQuery(null, "account_name", param.getAccountName());
        }

        IPage<UserOperateLog> page = userOperateLogManager.page(new Page<UserOperateLog>(currentPage, pageSize).setDesc("id"), query);
        return new JSONObject().fluentPut("total", page.getTotal())
                .fluentPut("records", page.getRecords());
    }

    public void userLoginDelete(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }
        userLoginLogManager.removeByIds(ids);
    }

    public void userOperateDelete(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }
        userOperateLogManager.removeByIds(ids);
    }

    private void download(Workbook wb, HttpServletResponse response, String filename) throws IOException {
        OutputStream out = response.getOutputStream();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-disposition", String.format("attachment; filename=%s", filename));
        if (null != out) {
            wb.write(out);
            out.flush();
        }
    }

    public void userLoginDownload(List<Long> ids, HttpServletResponse response) throws IOException {
        if (ids == null || ids.isEmpty()) {
            return;
        }

        Workbook wb = null;
        try {
            Collection<UserLoginLog> userLoginLogs = userLoginLogManager.listByIds(ids);
            List<UserLoginLog> userLoginLogList = new ArrayList<>(userLoginLogs);
            wb = ExcelExportUtil.exportWorkbook(userLoginLogList);
            download(wb, response, "test.xls");
        } finally {
            if (wb != null) {
                wb.close();
            }
            if (response != null && response.getOutputStream() != null) {
                response.getOutputStream().close();
            }
        }
    }

    public void userLoginDayDownload(Integer day, HttpServletResponse response) throws IOException {
        if (day != 3 && day != 7 && day != 15) {
            return;
        }

        DateTime todayMax = DateTimeUtil.maxOfDay(DateTime.now());
        DateTime todayMin = DateTimeUtil.minOfDay(DateTime.now());
        DateTime minDate = todayMin.minusDays(day - 1);

        Workbook wb = null;
        try {
            Collection<UserLoginLog> userLoginLogs = userLoginLogManager.getByDate(minDate.toDate(), todayMax.toDate());
            List<UserLoginLog> userLoginLogList = new ArrayList<>(userLoginLogs);
            wb = ExcelExportUtil.exportWorkbook(userLoginLogList);
            download(wb, response, "test.xls");
        } finally {
            if (wb != null) {
                wb.close();
            }
            if (response != null && response.getOutputStream() != null) {
                response.getOutputStream().close();
            }
        }
    }

    public void userOperateDownload(List<Long> ids, HttpServletResponse response) throws IOException {
        if (ids == null || ids.isEmpty()) {
            return;
        }

        Workbook wb = null;
        try {
            Collection<UserOperateLog> userOperateLogs = userOperateLogManager.listByIds(ids);
            List<UserOperateLog> userOperateLogList = new ArrayList<>(userOperateLogs);
            wb = ExcelExportUtil.exportWorkbook(userOperateLogList);
            download(wb, response, "test.xls");
        } finally {
            if (wb != null) {
                wb.close();
            }
            if (response != null && response.getOutputStream() != null) {
                response.getOutputStream().close();
            }
        }
    }

    public void userOperateDownload(Integer day, HttpServletResponse response) throws IOException {
        if (day != 3 && day != 7 && day != 15) {
            return;
        }

        DateTime todayMax = DateTimeUtil.maxOfDay(DateTime.now());
        DateTime todayMin = DateTimeUtil.minOfDay(DateTime.now());
        DateTime minDate = todayMin.minusDays(day - 1);

        Workbook wb = null;
        try {
            Collection<UserOperateLog> userOperateLogs = userOperateLogManager.getByDate(minDate.toDate(), todayMax.toDate());
            List<UserOperateLog> userOperateLogList = new ArrayList<>(userOperateLogs);
            wb = ExcelExportUtil.exportWorkbook(userOperateLogList);
            download(wb, response, "test.xls");
        } finally {
            if (wb != null) {
                wb.close();
            }
            if (response != null && response.getOutputStream() != null) {
                response.getOutputStream().close();
            }
        }
    }
}
